<template>
  <div class="supplier-table">
    <div style="margin-bottom: 10px;">
      <el-button type="primary" @click="handleCreateSupplier">新增供应商</el-button>
    </div>
    <el-table border :data="suppliers" stripe style="width: 100%">
      <!-- 供应商名称列 -->
      <el-table-column label="供应商名称" prop="name" width="180" />

      <!-- 联系电话列 -->
      <el-table-column label="联系电话" prop="phone" width="150" />

      <!-- 供应仓库列 -->
      <el-table-column label="供应商品" prop="products">
        <template #default="{ row }">
          <el-tag v-for="(product, index) in row.products" :key="index" class="product-tag" type="info">
            {{ product }}
          </el-tag>
        </template>
      </el-table-column>
      <!-- 合作状态 -->
      <el-table-column label="合作状态" prop="cooperation_status" width="100">
        <template #default="{ row }">
          <el-tag :type="statusTagMap[row.cooperation_status]">
            {{ statusMap[row.cooperation_status] }}
          </el-tag>
        </template>
      </el-table-column>
      <!-- 累计订单 -->
      <el-table-column label="累计订单" prop="num" width="100" />
      <!-- 操作列 -->
      <el-table-column align="center" label="操作" width="260">
        <template #default="{ row }">
          <el-button icon="el-icon-edit" size="mini" type="text" @click="handleEdit(row)">编辑</el-button>
          <el-button icon="el-icon-delete" size="mini" type="text" @click="handleDelete(row)">删除</el-button>
          <el-button icon="el-icon-shopping-cart-2" size="mini" type="text" @click="handleCreateOrder(row)">发起订单</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑供应商弹窗 -->
    <el-dialog :title="`编辑供应商 - ${currentSupplier?.name || '未知供应商'}`" :visible.sync="editDialogVisible" width="600px" @closed="resetCurrentSupplier">
      <el-form ref="editForm" label-width="100px" :model="currentSupplier" :rules="supplierRules">
        <el-form-item label="供应商名称" prop="name">
          <el-input v-model="currentSupplier.name" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="currentSupplier.phone" />
        </el-form-item>
        <el-form-item label="合作状态" prop="cooperation_status">
          <el-select v-model="currentSupplier.cooperation_status">
            <el-option v-for="(value, key) in statusMap" :key="key" :label="value" :value="Number(key)" />
          </el-select>
        </el-form-item>
        <el-form-item label="供应商品" prop="products">
          <el-select v-model="currentSupplier.products" allow-create filterable multiple placeholder="请输入或选择仓库" style="width: 100%;" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">保存</el-button>
      </template>
    </el-dialog>

    <!-- 发起订单弹窗 -->
    <el-dialog :title="`发起订单 - ${currentOrder.supplierName}`" :visible.sync="orderDialogVisible" width="600px" @closed="resetCurrentOrder">
      <el-form ref="orderForm" label-width="100px" :model="currentOrder" :rules="orderRules">
        <el-form-item label="供应商" prop="supplierName">
          <el-input disabled :value="currentOrder.supplierName" />
        </el-form-item>
        <el-form-item label="商品/仓库" prop="product">
          <el-select v-model="currentOrder.product" placeholder="请选择商品/仓库" style="width: 100%;">
            <el-option v-for="(product, index) in currentOrder.availableProducts" :key="index" :label="product" :value="product" />
          </el-select>
        </el-form-item>
        <el-form-item label="单据类型" prop="orderType">
          <el-select v-model="currentOrder.orderType" placeholder="请选择单据类型" style="width: 100%;">
            <el-option label="普通采购单" value="normal" />
            <el-option label="销售集采单" value="sales" />
          </el-select>
        </el-form-item>
        <el-form-item label="数量" prop="quantity">
          <el-input-number v-model="currentOrder.quantity" controls-position="right" :max="1000" :min="1" />
        </el-form-item>
        <el-form-item label="物流单号" prop="logisticsNo">
          <el-input v-model="currentOrder.logisticsNo" placeholder="请输入物流单号" />
        </el-form-item>
        <el-form-item label="入库仓库" prop="warehouse">
          <el-select v-model="currentOrder.warehouse" filterable placeholder="请选择入库仓库" style="width: 100%;">
            <el-option v-for="item in warehouseOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="currentOrder.remarks" placeholder="请输入备注信息" :rows="2" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="orderDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitOrder">提交订单</el-button>
      </template>
    </el-dialog>

    <!-- 新建供应商弹窗 -->
    <el-dialog title="新建供应商" :visible.sync="createDialogVisible" width="600px" @closed="resetNewSupplier">
      <el-form ref="createForm" label-width="100px" :model="newSupplier" :rules="supplierRules">
        <el-form-item label="供应商名称" prop="name">
          <el-input v-model="newSupplier.name" placeholder="请输入供应商名称" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="newSupplier.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="合作状态" prop="cooperation_status">
          <el-select v-model="newSupplier.cooperation_status">
            <el-option v-for="(value, key) in statusMap" :key="key" :label="value" :value="Number(key)" />
          </el-select>
        </el-form-item>
        <el-form-item label="供应商品" prop="products">
          <el-select v-model="newSupplier.products" allow-create filterable multiple placeholder="请输入或选择仓库，可创建新仓库" style="width: 100%;" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitCreate">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import Dexie from 'dexie';
import db from '@/db'; // 引入 Dexie 实例

export default {
  name: 'SupplierTable',
  data() {
    return {
      suppliers: [], // 数据将从 IndexedDB 加载
      statusMap: {
        1: '合作中',
        2: '已暂停',
        3: '黑名单',
      },
      statusTagMap: {
        1: 'success',
        2: 'warning',
        3: 'danger',
      },
      createDialogVisible: false,
      newSupplier: {
        name: '',
        phone: '',
        products: [], // 修改为数组
        cooperation_status: 1,
        // num: 0, // num 会在创建订单时更新，初始不需要
      },
      editDialogVisible: false,
      currentSupplier: { // 用于编辑的供应商对象
        id: null,
        name: '',
        phone: '',
        products: [],
        cooperation_status: 1,
        num: 0,
      },
      orderDialogVisible: false,
      currentOrder: {
        supplierId: null,
        supplierName: '',
        product: '',
        availableProducts: [],
        quantity: 1,
        remarks: '',
        orderType: 'normal', // 默认为普通采购单
        logisticsNo: '',
        warehouse: '',
        warehouseLabel: '',
      },
      // 添加仓库选项，将在created中加载
      warehouseOptions: [],
      orderRules: {
        supplierName: [{ required: true, message: '供应商信息错误', trigger: 'blur' }],
        product: [{ required: true, message: '请选择商品/仓库', trigger: 'change' }],
        quantity: [{ required: true, message: '请输入数量', trigger: 'blur' }],
        orderType: [{ required: true, message: '请选择单据类型', trigger: 'change' }],
        warehouse: [{ required: true, message: '请选择入库仓库', trigger: 'change' }],
      },
    }
  },
  async created() {
    await this.getList();
    // 加载仓库数据
    this.loadWarehouseOptions();
    // 可以在这里添加一些初始数据，如果数据库为空
    if (this.suppliers.length === 0) {
      await this.addInitialData();
      await this.getList(); // 重新获取列表
    }

    // 监听仓库数据变化
    window.addEventListener('storageUpdated', (e) => {
      if (e.detail.key === 'warehouseTableData') {
        this.loadWarehouseOptions();
      }
    });

    window.addEventListener('storage', (e) => {
      if (e.key === 'warehouseTableData') {
        this.loadWarehouseOptions();
      }
    });
  },
  beforeDestroy() {
    window.removeEventListener('storageUpdated', this.handleStorageUpdate);
    window.removeEventListener('storage', this.handleStorageUpdate);
  },
  methods: {
    // 添加处理存储更新的方法
    handleStorageUpdate(e) {
      if ((e.detail && e.detail.key === 'warehouseTableData') ||
          (e.key === 'warehouseTableData')) {
        this.loadWarehouseOptions();
      }
    },

    // 添加加载仓库选项的方法
    loadWarehouseOptions() {
      const warehouseData = localStorage.getItem('warehouseTableData')
      if (warehouseData) {
        const warehouses = JSON.parse(warehouseData)
        this.warehouseOptions = warehouses.map(warehouse => ({
          value: `WH_${warehouse.id}`,
          label: warehouse.name
        }))
      } else {
        // 如果没有数据，使用默认值
        this.warehouseOptions = [
          { value: 'WH_001', label: '北京中心仓' },
          { value: 'WH_002', label: '上海配送中心' },
          { value: 'WH_003', label: '广州物流仓' },
          { value: 'WH_004', label: '深圳分仓' },
        ]
      }
    },
    async addInitialData() {
      const initialSuppliers = [
        { name: 'ABC 供应商', phone: '13812345678', products: ['仓库A', '仓库B'], cooperation_status: 1, num: 100, createdAt: new Date() },
        { name: 'XYZ 有限公司', phone: '13987654321', products: ['仓库X'], cooperation_status: 2, num: 50, createdAt: new Date() },
      ];
      try {
        await db.suppliers.bulkAdd(initialSuppliers);
        this.$message.success('初始数据添加成功');
      } catch (error) {
        console.error('添加初始数据失败:', error);
        // 如果是因为唯一索引冲突，可以忽略
        if (error.name !== 'ConstraintError') {
          this.$message.error('添加初始数据失败');
        }
      }
    },
    async getList() {
      try {
        // 按创建时间降序排列
        this.suppliers = await db.suppliers.orderBy('createdAt').reverse().toArray();
      } catch (error) {
        console.error('获取供应商列表失败:', error);
        this.$message.error('获取供应商列表失败');
      }
    },
    resetNewSupplier() {
      this.newSupplier = {
        name: '',
        phone: '',
        products: [],
        cooperation_status: 1,
      };
      if (this.$refs.createForm) {
        this.$refs.createForm.resetFields();
      }
    },
    resetCurrentSupplier() {
      this.currentSupplier = {
        id: null,
        name: '',
        phone: '',
        products: [],
        cooperation_status: 1,
        num: 0,
      };
       if (this.$refs.editForm) {
        this.$refs.editForm.resetFields();
      }
    },
    resetCurrentOrder() {
      this.currentOrder = {
        supplierId: null,
        supplierName: '',
        product: '',
        availableProducts: [],
        quantity: 1,
        remarks: '',
        orderType: 'normal',
        logisticsNo: '',
        warehouse: '',
        warehouseLabel: '',
      };
      if (this.$refs.orderForm) {
        this.$refs.orderForm.resetFields();
      }
    },
    handleCreateSupplier() {
      this.resetNewSupplier();
      this.createDialogVisible = true;
    },
    async submitCreate() {
      this.$refs.createForm.validate(async (valid) => {
        if (valid) {
          try {
            const supplierToCreate = {
              ...this.newSupplier,
              num: 0, // 新供应商累计订单初始为0
              createdAt: new Date() // 添加创建时间
            };
            await db.suppliers.add(supplierToCreate);
            this.$message.success('供应商创建成功');
            this.createDialogVisible = false;
            await this.getList(); // 刷新列表
          } catch (error) {
            console.error('创建供应商失败:', error);
            if (error.name === 'ConstraintError') {
              this.$message.error('供应商名称已存在，请使用其他名称');
            } else {
              this.$message.error('供应商创建失败');
            }
          }
        }
      });
    },
    handleEdit(row) {
      // 深拷贝，避免直接修改列表中的数据影响视图，直到保存
      this.currentSupplier = JSON.parse(JSON.stringify(row));
      this.editDialogVisible = true;
    },
    async submitEdit() {
      this.$refs.editForm.validate(async (valid) => {
        if (valid) {
          try {
            const { id, ...updates } = this.currentSupplier;
            await db.suppliers.update(id, updates);
            this.$message.success('供应商信息更新成功');
            this.editDialogVisible = false;
            await this.getList(); // 刷新列表
          } catch (error) {
            console.error('更新供应商失败:', error);
             if (error.name === 'ConstraintError') {
              this.$message.error('供应商名称已存在，请使用其他名称');
            } else {
              this.$message.error('供应商信息更新失败');
            }
          }
        }
      });
    },
    async handleDelete(row) {
      try {
        await this.$confirm(`确定要删除供应商 "${row.name}" 吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        });
        await db.suppliers.delete(row.id);
        this.$message.success('删除成功!');
        await this.getList(); // 刷新列表
      } catch (error) {
        // 如果用户点击取消，confirm会抛出错误，这里捕获并判断
        if (error !== 'cancel') {
          console.error('删除供应商失败:', error);
          this.$message.error('删除失败，请重试');
        }
      }
    },
    handleCreateOrder(row) {
      this.resetCurrentOrder();
      this.currentOrder = {
        supplierId: row.id,
        supplierName: row.name,
        product: row.products && row.products.length > 0 ? row.products[0] : '', // 默认选中第一个商品/仓库
        availableProducts: [...row.products],
        quantity: 1,
        remarks: '',
        orderType: 'normal',
        logisticsNo: `LG${Math.random().toString(36).substr(2, 8).toUpperCase()}`, // 生成随机物流单号
        warehouse: this.warehouseOptions[0].value, // 默认选择第一个仓库
        warehouseLabel: this.warehouseOptions[0].label,
      };
      this.orderDialogVisible = true;
    },
    async submitOrder() {
      this.$refs.orderForm.validate(async (valid) => {
        if (valid) {
          try {
            // 更新累计订单数
            const supplier = this.suppliers.find((s) => s.id === this.currentOrder.supplierId);
            if (supplier) {
              // 更新供应商的订单数量
              supplier.num += this.currentOrder.quantity;

              // 更新数据库中的供应商数据
              await db.suppliers.update(this.currentOrder.supplierId, {
                num: supplier.num
              });
            }

            // 获取选中仓库的标签
            const selectedWarehouse = this.warehouseOptions.find(w => w.value === this.currentOrder.warehouse);
            const warehouseLabel = selectedWarehouse ? selectedWarehouse.label : '';

            // 获取选中单据类型的标签
            const orderTypeLabel = this.currentOrder.orderType === 'normal' ? '普通采购单' : '销售集采单';

            // 创建新订单对象，格式与采购管理页面一致
            const newOrder = {
              orderNo: `PO${new Date().getFullYear()}${String(Date.now()).substr(-6)}`, // 生成订单编号
              orderType: this.currentOrder.orderType,
              orderTypeLabel: orderTypeLabel,
              supplier: this.currentOrder.supplierId,
              supplierLabel: this.currentOrder.supplierName,
              warehouse: this.currentOrder.warehouse,
              warehouseLabel: warehouseLabel,
              status: '待审核', // 新订单默认为待审核状态
              logisticsNo: this.currentOrder.logisticsNo,
              quantity: this.currentOrder.quantity,
              createTime: new Date().toLocaleString('zh-CN', { hour12: false }),
              creator: '当前用户', // 这里可以替换为实际的用户名
              productName: this.currentOrder.product, // 添加商品名称
              remarks: this.currentOrder.remarks, // 添加备注信息
            };

            // 从localStorage获取现有订单数据
            let purchaseData = [];
            const storedData = localStorage.getItem('purchaseTableData');
            if (storedData) {
              purchaseData = JSON.parse(storedData);
            }

            // 添加新订单到数据列表的开头
            purchaseData.unshift(newOrder);

            // 保存回localStorage
            localStorage.setItem('purchaseTableData', JSON.stringify(purchaseData));

            this.$message.success(`已成功为${this.currentOrder.supplierName}创建订单`);
            this.orderDialogVisible = false;
          } catch (error) {
            console.error('创建订单失败:', error);
            this.$message.error('创建订单失败，请重试');
          }
        }
      });
    },
  },
}
</script>

<style scoped>
  .supplier-table {
    padding: 20px;
  }

  .product-tag {
    margin: 2px;
  }

  .el-button + .el-button {
    margin-left: 8px;
  }
</style>
